<template>
  <div :id="`ringModule${chartId}`" class="ring-module" style="width: 100%; height: 100%">
    <template v-for="(curName, index) in moduleNames">
      <div :key="index" :class="`chart-base-box${moduleNames.length}`" class="chart-base-box">
        <div :style="{color: getStyleConfigColor, fontSize: getStyleConfigFontSize('tagTitle')}" :title="curName" class="chart-title ellipsisOne">{{ curName }}</div>
        <div :id="`chartContentBox${chartId}`" class="chart-content-box">
          <div :id="`echartPie${chartId + '' + index}`" class="chart-render-box"/>
        </div>
        <div :style="{ fontSize: getStyleConfigFontSize('contentText'), lineHeight: getStyleConfigFontSize('contentText') }" style="display: inline-block; vertical-align: top;">
          <div v-if="columns[index] || rowsFlat[index]" class="item-contrast">
            <span class="title">{{ columns[index] }}</span>
            <span class="progress-value">{{ rowsFlat[index] }}</span>
          </div>
          <div v-if="getContrastValue(index, 'monthOnMonthData') || (monthOnMonthTitle && monthOnMonthTitle[index])" class="item-contrast">
            <span class="title">{{ monthOnMonthTitle[index] }}</span>
            <i v-if="getContrastValue(index, 'monthOnMonthData') < 0" class="icon el-icon-caret-bottom" style="color:green;"/>
            <i v-else-if="getContrastValue(index, 'monthOnMonthData')" class="icon el-icon-caret-top" style="color:red;"/>
            <span v-if="getContrastValue(index, 'monthOnMonthData') || getContrastValue(index, 'monthOnMonthData') === 0" :style="textColor(index, 'monthOnMonthData')" class="value">{{ getContrastValue(index, 'monthOnMonthData') }}%</span>
            <span v-else class="value">--</span>
          </div>
          <div v-if="getContrastValue(index, 'yearOnYearData') || (yearOnYearTitle && yearOnYearTitle[index])" class="item-contrast">
            <span class="title">{{ yearOnYearTitle[index] }}</span>
            <i v-if="getContrastValue(index, 'yearOnYearData') && getContrastValue(index, 'yearOnYearData') < 0" class="icon el-icon-caret-bottom" style="color:green;"/>
            <i v-else-if="getContrastValue(index, 'yearOnYearData')" class="icon el-icon-caret-top" style="color:red;"/>
            <span v-if="getContrastValue(index, 'yearOnYearData') || getContrastValue(index, 'yearOnYearData') === 0" :style="textColor(index, 'yearOnYearData')" class="value">{{ getContrastValue(index, 'yearOnYearData') }}%</span>
            <span v-else class="value">--</span>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
const ECHARTS = require('echarts/lib/echarts');
require('echarts/lib/component/polar');
require('echarts/lib/component/title');
import { numberTextFormat } from '@/filters/number';
export default {
  name: 'RingItemModule',
  props: {
    moduleItemData: {
      type: Object,
      default: () => ({})
    },
    styleConfig: {
      type: [Array, Object],
      default: () => ({})
    }
  },
  data() {
    return {
      baseOptions: {
        backgroundColor: 'transparent',
        // title: {
        //   text: '',
        //   left: 'center',
        //   top: 'center',
        //   textStyle: {
        //     color: '#333',
        //     fontSize: 24
        //   },
        //   subtext: '',
        //   subtextStyle: {
        //     color: '#999',
        //     fontSize: 16
        //   }
        // },
        polar: {
          radius: ['65%', '80%'],
          center: ['50%', '50%']
        },
        // 极坐标角度轴
        angleAxis: {
          min: 0,
          max: 100,
          clockwise: true,
          show: false // 隐藏刻度线
        },
        // 极坐标径向轴
        radiusAxis: {
          type: 'category',
          // 隐藏极坐标轴线
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        // tooltip: {
        //   show: true,
        //   formatter: val => {
        //     return `完成率: ${val.data}%`;
        //   },
        //   backgroundColor: 'rgba(0, 0, 0, .25)'
        // },
        series: [{
          // 进度条
          type: 'bar',
          coordinateSystem: 'polar',
          showBackground: true,
          // barMaxWidth: 25,
          backgroundStyle: {
            color: 'rgb(64, 110, 255)',
            opacity: 0.05
          },
          // 两端设置圆角
          roundCap: true,
          itemStyle: {
            color: 'rgb(64, 110, 255)'
          },
          data: []
        }, {
          type: 'pie',
          radius: ['80%', '80%'],
          center: ['48%', '52%'],
          data: [{
            label: {
              normal: {
                show: true,
                position: 'center',
                formatter: '',
                rich: {
                  aa: {
                    color: '#333',
                    fontSize: '70',
                    fontWeight: 'bold'
                  },
                  bb: {
                    color: '#999',
                    fontSize: '28'
                  }
                }
              }
            }
          }]
        }]
      },
      chartId: '',
      columns: [], // 进度数据名
      rows: [], // 进度数据
      monthOnMonthData: [], // 环比数据
      yearOnYearData: [], // 同比数据
      monthOnMonthTitle: [], // 环比标题
      yearOnYearTitle: [], // 同比标题
      targetPercentData: [], // 目标数据
      targetNames: [], // 目标数据名称
      themeColors: [], // 主题色
      moduleNames: [], // 圆环图模块名称
      allChart: []
    };
  },
  computed: {
    chartDataKeys() {
      return ['targetPercentData', 'targetNames', 'themeColors', 'moduleNames', 'monthOnMonthData', 'yearOnYearData', 'monthOnMonthTitle', 'yearOnYearTitle', 'columns', 'rows'];
    },
    getStyleConfigColor() {
      return this.styleConfig['tagTitle'] && this.styleConfig['tagTitle'].color;
    },
    rowsFlat() {
      const rowsFlat = this.rows.flat(Infinity);
      rowsFlat.forEach((val, index) => {
        const valToNum = Number(val);
        if (!isNaN(valToNum)) {
          rowsFlat[index] = numberTextFormat(valToNum);
        }
      });
      return rowsFlat;
    }
  },
  watch: {
    moduleItemData: {
      handler(data) {
        this.chartId = data.id;
        this.chartDataKeys.forEach(key => {
          this[key] = this.getChartData(data, key);
        });
        this.$nextTick(() => {
          this.initEcharts();
        });
      },
      deep: true,
      immediate: true
    }
  },
  beforeMount() {
    window.addEventListener('resize', this.resetEchart);
  },
  methods: {
    getChartData(data, type) {
      return data && data.tableData && data.tableData[type] || [];
    },
    initEcharts() {
      for (let i = 0; i < this.moduleNames.length; i++) {
        const chartDom = document.getElementById(`echartPie${this.chartId + '' + i}`);
        if (!chartDom) continue;
        const chartEntity = ECHARTS.init(chartDom);
        const chartOptions = this.formatOptions(i);
        chartEntity.setOption(chartOptions);
        this.allChart.push(chartEntity);
      }
      this.$nextTick(() => {
        this.resetEchart();
      });
    },
    formatOptions(index) {
      const curOptions = JSON.parse(JSON.stringify(this.baseOptions));
      // curOptions.title.text = this.formatTitleText(index);
      // curOptions.title.subtext = this.targetNames[index] || '--';
      // curOptions.title.textStyle.fontSize = this.styleConfig['targetText'] && this.styleConfig['targetText']['dataFontSize'];
      // curOptions.title.subtextStyle.fontSize = this.styleConfig['targetText'] && this.styleConfig['targetText']['titleFontSize'];
      curOptions.series[1].data[0].label.normal.rich.aa.fontSize = this.styleConfig['targetText'] && this.styleConfig['targetText']['dataFontSize'];
      curOptions.series[1].data[0].label.normal.rich.bb.fontSize = this.styleConfig['targetText'] && this.styleConfig['targetText']['titleFontSize'];
      curOptions.series[1].data[0].label.normal.rich.bb.lineHeight = this.styleConfig['targetText'] && this.styleConfig['targetText']['titleFontSize'] + 4;
      curOptions.series[1].data[0].label.normal.formatter = `{aa| ${this.formatTitleText(index)}}\n{bb| ${this.targetNames[index] || '--'}}`;
      curOptions.series[0].itemStyle.color = this.themeColors[index];
      curOptions.series[0].backgroundStyle.color = this.themeColors[index];
      const targetPercentValue = this.targetPercentData[index].value < 0 ? 0 : this.targetPercentData[index].value > 100 ? 100 : this.targetPercentData[index].value;
      curOptions.series[0].data.push(targetPercentValue);
      return curOptions;
    },
    formatTitleText(index) {
      let { value } = this.targetPercentData[index];
      const { unit } = this.targetPercentData[index];
      if (value == null || value === '') {
        return '--';
      }
      const valueToNum = Number(value);
      if (value !== 0 && !isNaN(valueToNum) && !Number.isInteger(value)) {
        value = value.toFixed(1);
      }
      return value + unit;
    },
    resetEchart() {
      this.allChart.forEach((chart, index) => {
        // 适配拖拽盒子高度变化后重置图表
        const outBoxHeight = document.querySelector(`#ringModule${this.moduleItemData.id}`).clientHeight;
        const curChartDom = document.querySelector(`#echartPie${this.moduleItemData.id + '' + index}`);
        const chartWidth = curChartDom.clientWidth;
        const chartBox = document.querySelectorAll(`#chartContentBox${this.moduleItemData.id}`)[index];
        if (chartWidth + 100 > outBoxHeight) {
          chartBox.style.setProperty('width', `${outBoxHeight - 100}px`, 'important');
          chartBox.style.setProperty('height', `${outBoxHeight - 100}px`, 'important');
          chartBox.style.setProperty('padding-bottom', `0`, 'important');
        } else {
          chartBox.style.setProperty('width', `100%`);
          chartBox.style.setProperty('height', `0`);
          chartBox.style.setProperty('padding-bottom', `100%`);
          const _outBoxHeight = document.querySelector(`#ringModule${this.moduleItemData.id}`).clientHeight;
          const _curChartDom = document.querySelector(`#echartPie${this.moduleItemData.id + '' + index}`);
          const _chartWidth = _curChartDom.clientWidth;
          const _chartBox = document.querySelectorAll(`#chartContentBox${this.moduleItemData.id}`)[index];
          if (_chartWidth + 100 > _outBoxHeight) {
            _chartBox.style.setProperty('width', `${_outBoxHeight - 100}px`, 'important');
            _chartBox.style.setProperty('height', `${_outBoxHeight - 100}px`, 'important');
            _chartBox.style.setProperty('padding-bottom', `0`, 'important');
          }
        }
        chart.resize();
      });
    },
    getContrastValue(index, type) {
      if (this[type] && (this[type][index] || this[type][index] === 0)) {
        return this[type][index];
      }
      return null;
    },
    getStyleConfigFontSize(type) {
      const fontSize = this.styleConfig[type] && this.styleConfig[type].fontSize;
      return fontSize && (fontSize + 'px');
    },
    textColor(index, type) {
      if (this.getContrastValue(index, type) < 0) {
        return { color: 'green' };
      } else if (this.getContrastValue(index, type)) {
        return { color: 'red' };
      }
      return {};
    }
  }
};
</script>

<style lang="scss" scoped>
$widthPercent:
  100% 1,
  50% 2,
  33.3% 3;
.ring-module {
  display: flex;
  flex-wrap: wrap;
  @each $percent, $num in $widthPercent {
    .chart-base-box#{$num} {
      width: $percent !important;
    }
  }
  .chart-base-box {
    width: 25%;
    min-width: 100px;
    min-height: 100px;
    text-align: center;
    .chart-title {
      display: inline-block;
      width: 100%;
      text-align: left;
      font-weight: bold;
    }
    .chart-content-box {
      width: 100%;
      height: 0;
      padding-bottom: 100%;
      position: relative;
      margin: 0 auto;
      .chart-render-box {
        position: absolute;
        left: 0; top: 0; bottom: 0; right: 0;
      }
    }
    .item-contrast {
      display: flex;
      align-items: center;
      margin-top: 0;
      margin-bottom: 8px;
      .title {
        //font-size: 14px;
        color: #999;
        white-space: nowrap;
      }
      .icon {
        //font-size: 20px;
        margin-left: 2px;
        position: relative;
        top: 1px;
      }
      .value {
        margin-left: 2px;
        //font-size: 14px;
      }
      .progress-value {
        margin-left: 8px;
        color: #333;
        white-space: nowrap;
      }
    }
  }
}
</style>
